import { Injectable, Inject } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { CacheService, NGW_CACHE_TOKEN } from '../cache/CacheService';

export const KEY_JWT_TOKEN: string = "__jwt_token";

@Injectable()
export class AuthenticationInterceptor implements HttpInterceptor {

    constructor(
        @Inject(NGW_CACHE_TOKEN) private cache: CacheService) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const idToken = this.getToken();

        if (idToken) {
            const cloned = req.clone({
                headers: req.headers.set('Authorization', 'Bearer ' + idToken)
            });

            return next.handle(cloned);
        } else {
            return next.handle(req);
        }
    }

    getToken(): string {
        const userStr = this.cache.get(KEY_JWT_TOKEN);
        return userStr ? userStr : '';
    }
}
